<template>
  <div>
    <el-form ref="form" class="dept-form" :model="deptForm" :rules="rules" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="deptForm.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="deptForm.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="deptForm.manager" placeholder="请选择部门负责人">
          <el-option
            v-for="item in employees"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="deptForm.introduce" type="textarea" />
      </el-form-item>

      <el-form-item>
        <el-button size="mini" type="primary" @click="onSubmit">确定</el-button>
        <el-button size="mini" @click="calceSubmit">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
export default {
  name: 'DeptDialog',
  props: {
    parentId: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    // 验证编码是否重复
    const validCode = (rules, value, callback) => {
      // 首先将所有的编码组装成一个数组
      let existCodeList = this.originList.map(item => item.code)

      // 使用 includes 验证我们输入的编码是否在所有的编码中
      // 如果存在，说明重复，需要抛出错误
      // 如果不存在，直接调用 callback
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.code)
      }
      existCodeList.includes(value) ? callback(new Error('部门编码' + value + '已经存在')) : callback()
    }
    const validName = (rules, value, callback) => {
      let existNameList = this.originList.filter(item => item.pid === this.parentId).map(item => item.name)

      // 判断是否是编辑
      if (this.isEdit) {
        // 需要先获取编辑项本身， item.id === this.parentId
        const dept = this.originList.find(item => item.id === this.parentId)

        // 获取到 pid
        const pid = dept.pid

        // 使用 filter 筛选出 pid 一样的兄弟节点，但是需要排除本身
        // 使用 map 方法将兄弟节点的 name 组成一个新数组
        existNameList = this.originList
          .filter(item => item.pid === pid && item.id !== this.parentId)
          .map(item => item.name)
      }
      existNameList.includes(value) ? callback(new Error('部门名称' + value + '已经存在')) : callback()
    }

    return {
      deptForm: {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        manager: '', // 部门负责人
        name: '' // 部门名称
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      },
      employees: []
    }
  },
  // watch: {
  //   parentId() {
  //     this.getDepartDetail()
  //   }
  // },
  created() {
    // 调用获取负责人列表的方法
    this.getEmployeeSimple()
    // 获取部门详情
    this.getDepartDetail()
  },
  methods: {
    //   取消弹框
    calceSubmit() {
      this.$emit('closeDialog')
    },
    //   根据id获取当前部门数据
    async getDepartDetail() {
      if (this.isEdit) {
        const res = await getDepartDetail(this.parentId)
        this.deptForm = res.data
      }
    },
    // 添加部门
    onSubmit() {
      this.$refs.form.validate(async valid => {
        if (!valid) return

        if (this.isEdit) {
        // 编辑部门
        //   const params = { ...this.deptForm }
          await updateDepartments(this.deptForm)
        } else {
        // 组装参数
          const params = { ...this.deptForm, pid: this.parentId }
          await addDepartments(params)
        }
        // 弹框隐藏
        this.$emit('close')
        // 给用户提示
        this.$message.success(this.isEdit ? '编辑成功' : '添加成功')
      })
      // 刷新页面
    },

    // 获取负责人列表
    async getEmployeeSimple() {
      const res = await getEmployeeSimple()
      this.employees = res.data
    }
  }
}
</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.dept-form {
  padding: 0px 60px 0px 30px;
}
</style>
